package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            //判断方法上是否有自定义的登录验证注解
            if (method.hasMethodAnnotation(RequireLogin.class)) {
                //通过cookie拿到token
                String token = CookieUtil.getToken(request, response);
                //拿到当前登录的用户
                UserInfo user = userInfoRedisService.getUserByToken(token);
                if(user == null){
                    //没登录
                    response.sendRedirect("/login.html");
                    return false;
                }
                //拦截器通过检查登录权限,来实现每次拦截都查询最新用户信息,从而数据共享到缓存(cookie,session,redis)
                request.getSession().setAttribute("userInfo",user);
            }
        }
        return true;

    }
}
